<template>
  <div v-if="modelValue" class="preview-form">
    <div class="final-preview">
      <div class="final-preview-inner">
        <div class="preview-title">
          {{ page.title }}
        </div>
        <div class="iframe-container">
          <iframe
            :src="previewURL"
            class="iframe-placeholder"
            width="375"
            :height="page.props && page.props.height ? page.props.height : '560'"
            frameborder="0"
          ></iframe>
        </div>
      </div>
    </div>
    <el-drawer v-model="showDrawer" title="设置面板" :size="400" @close="onCancel">
      <div class="publish-form-container">
        <el-row align="middle" :style="{ marginBottom: '20px' }">
          <el-col :span="6">扫码预览：</el-col>
          <el-col :span="10">
            <canvas id="preview-barcode-container"></canvas>
          </el-col>
        </el-row>
        <el-row align="middle" :style="{ marginBottom: '20px' }">
          <el-col :span="6">上传封面：</el-col>
          <el-col :span="10">
            <styled-uploader
              text="上传封面"
              show-uploaded
              :uploaded="form.uploaded"
              @success="updateAvatar"
            ></styled-uploader>
          </el-col>
        </el-row>

        <el-form ref="previewForm" :model="form" :rules="rules">
          <el-form-item label="标题" required prop="title">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="描述" required prop="desc">
            <el-input v-model="form.desc" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="margin-left: 10px" :loading="saveIsLoading" @click="validateAndSave">
              保存
            </el-button>
            <el-button style="margin-left: 10px" @click="onCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { baseH5URL } from '@/service/request'
import { useEditorStore } from '@/stores/editor'
import useSaveWork from '@/hooks/useSaveWork'
import { generateQRCode, timeout } from '@/utils/utils'
import type { FormInstance, FormRules } from 'element-plus'
import { forEach } from 'lodash-es'

const props = withDefaults(defineProps<{ modelValue: boolean }>(), { modelValue: false })
const emit = defineEmits(['update:modelValue'])

const editor = useEditorStore()
const { saveWork, saveIsLoading } = useSaveWork(true)

const previewForm = ref<FormInstance>()

const page = computed(() => editor.page)
const showDrawer = computed(() => props.modelValue)
const previewURL = computed(() => `${baseH5URL}/p/${page.value.id}-${page.value.uuid}`)

const form = reactive({
  title: '',
  desc: '',
  uploaded: {
    data: {
      url: ''
    }
  }
})
const rules = reactive<FormRules>({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
})

watch(
  () => props.modelValue,
  async newVisible => {
    if (newVisible) {
      await timeout(100)
      await generateQRCode('preview-barcode-container', previewURL.value)
    }
  }
)

watch(
  () => page.value,
  () => {
    form.title = page.value.title || ''
    form.desc = page.value.desc || ''
    form.uploaded.data = {
      url:
        (page.value.setting && page.value.setting.shareImg) ||
        'http://lowcode-backend.oss-cn-shenzhen.aliyuncs.com/lowcode-test/9tiL7h.png'
    }
  }
)

const updateAvatar = (rawData: { url: string }) => {
  form.uploaded.data = { url: rawData.url }
}

const validateAndSave = async () => {
  try {
    await previewForm.value.validate()
    forEach(form, (value, key) => {
      if (key === 'uploaded' && typeof value !== 'string') {
        editor.updatePage({ key: 'shareImg', value: value.data.url, isSetting: true })
      } else {
        editor.updatePage({ key, value, isRoot: true })
      }
    })
    await saveWork()
    emit('update:modelValue', false)
  } catch (error) {
    console.error(error)
  }
}

const onCancel = () => {
  emit('update:modelValue', false)
}
</script>
<style lang="scss" scoped>
.final-preview {
  position: absolute;
  width: calc(100% - 400px);
  height: 100%;
  background: transparent;
  top: 0;
  left: 0;
  z-index: 3000;
  display: flex;
  align-items: center;
  justify-content: center;
}
.final-preview-inner {
  width: 430px;
  height: 870px;
  padding: 60px 28px;
  position: relative;
  background: url('@/assets/phone-back1.png') no-repeat;
  background-size: cover;
}

.final-preview-inner .preview-title {
  height: 44px;
  line-height: 44px;
  text-align: center;
  font-weight: bold;
}
.iframe-container {
  width: 100%;
  height: 706px;
  overflow-y: auto;
  overflow-x: hidden;
}
.iframe-placeholder {
  background: url('@/assets/loading.svg') 50% 50% no-repeat;
  background-size: 50px;
}
.publish-form-container .file-upload-container {
  height: 130px;
}
#preview-barcode-container {
  border: 2px dotted #efefef;
  padding: 10px;
}
</style>
